package com.qili.config;

import com.qili.interceptor.Authnterceptor;
import com.qili.interceptor.SessionInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;

/**
 * @author zhuxiaomeng
 * @date 2018/1/1.
 * @email 154040976@qq.com
 * spring shiro
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${supervisor.imagePath}")
    private String imagePath;
    @Value("${supervisor.uploadPath}")
    private String filePath;
    @Value("${supervisor.zbhtPath}")
    private String zbhtPath;
    @Value("${supervisor.personPath}")
    private String personPath;
    @Value("${supervisor.userPath}")
    private String userPath;
    @Value("${supervisor.batchPath}")
    private String batchPath;

    @Value("${supervisor.fileTempPath}")
    private String fileTempPath;

    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }


//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//        super.configureMessageConverters(converters);
//        converters.add(responseBodyConverter());
//    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.extendMessageConverters(converters);
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) converter;
                stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
            }
        }
    }




    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
        registry.addResourceHandler("/plugin/**", "/static/**")
                .addResourceLocations("classpath:/plugin/", "classpath:/static/");
        registry.addResourceHandler("/ftl/**").addResourceLocations("classpath:/ftl/");
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + filePath + personPath + '/');
        registry.addResourceHandler("/userfile/**").addResourceLocations("file:" + filePath + userPath + '/');
        registry.addResourceHandler("/img/**").addResourceLocations("file:" + filePath + personPath + '/');
        registry.addResourceHandler("/imgs/**").addResourceLocations("file:" + filePath + imagePath + '/');
        registry.addResourceHandler("/file/**").addResourceLocations("file:" + filePath + personPath + '/');
        registry.addResourceHandler("/imagefiletemp/**").addResourceLocations("file:" + fileTempPath + '/');

        registry.addResourceHandler("/batch/**").addResourceLocations("file:" + filePath + batchPath + '/');
        registry.addResourceHandler("/itfile/**").addResourceLocations("file:" + filePath);
        super.addResourceHandlers(registry);
    }

    /*保留国际化*/
    @Bean
    public LocaleChangeInterceptor interceptor() {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang");
        return interceptor;
    }

    /**
     * 此方法把该拦截器实例化成一个bean,否则在拦截器里无法注入其它bean
     * @return
     */
    @Bean
    SessionInterceptor sessionInterceptor() {
        return new SessionInterceptor();
    }


    /**
    * @Author:zhaoyongke
    * @Description:  app token校验
    * @param
    * @Date:9:39 2021/11/19
    */
    @Bean
     public Authnterceptor authnterceptor(){
        return  new Authnterceptor();
     }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //不需要拦截的请求
        String[] excludePathPatterns = {"/app/login","/app/getCode"};
//        registry.addInterceptor(sessionInterceptor())
//                .addPathPatterns("/**")
//                .excludePathPatterns("/login","/error");
          registry.addInterceptor(authnterceptor())
              .addPathPatterns("/app/**")
             .excludePathPatterns(excludePathPatterns);
        registry.addInterceptor(interceptor());
    }

    @Bean
    public LocaleResolver resolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.US);
        return resolver;
    }


    /**
     * @Author:zengyuli
     * @Description:解决跨域问题
     * @param
     * @Date:14:00 2021/9/24
     */
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
    /**
     * 跨域
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*");

    }
}
